<script setup lang="ts">
import {Back} from "@element-plus/icons-vue";
import {useRoute, useRouter} from "vue-router";
import {reactive, ref} from "vue";
import type {FaceDataInfo} from '@/types'
import api from '@/api/index'
import {ElMessage} from "element-plus";
import type {FormRules} from "element-plus";
import type {UploadProps} from 'element-plus'


const router = useRouter();
const route = useRoute();


const namespace = ref<string>(<string>route.params.namespace)
const collectionName = ref<string>(<string>route.params.collectionName)
const sampleId = ref<string>(<string>route.params.sampleId)


const addColumn = () => {
  faceDataInfo.faceData.push({key: '', value: ''})
}
const deleteColumn = () => {
  faceDataInfo.faceData.length > 1 ? faceDataInfo.faceData.pop() : ElMessage.error('至少保留一条数据')
}

let faceDataInfo = reactive({
  namespace: namespace.value,
  collectionName: collectionName.value,
  sampleId: sampleId.value,
  imageBase64: '',
  faceData: [{key: 'label', value: ''}],
  faceScoreThreshold: 0,
  maxConfidenceThresholdWithOtherSample: 50,
  minConfidenceThresholdWithThisSample: 0
})

const addFaceData = () => {
  if (verify(null,null,null)) {
    api.addFaceData(faceDataInfo)
        .then((res) => {
          if (res.data.code === 0) {
            ElMessage.success('添加成功')
            router.push('/sample')
          } else {
            ElMessage.error(res.data.message)
          }
        })
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 匹配rawFile 的类型是否是image
  if (!rawFile.type.includes('image')) {
    ElMessage.error('上传文件必须是图片')
    return false
  }
  const reader = new FileReader()
  reader.onload = function (e) {
    typeof reader.result === "string" ? faceDataInfo.imageBase64 = reader.result : faceDataInfo.imageBase64 = ''
  }
  reader.readAsDataURL(rawFile)
  return true
}


const regs = {
  // 小写字母、数字和下划线
  name: /^[a-z0-9_]+$/,
  id: /^[a-zA-Z0-9]+$/,
  email: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
  number: /^([0]|[1-9][0-9]*)$/,
  password: /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*_]{8,}$/,
  shareCode: /^[A-Za-z0-9]+$/
}


const verify = (rule: any, value: any, callback: any) => {
  if(callback!=null){
    for (let i = 0; i < value.length; i++) {
      let data = value[i]
      let note = 'faceData[' + i + ']'
      if (data.key.trim().length < 1 || data.key.trim().length > 32 || !regs.name.test(data.key)) {
        callback(new Error(note + '.key 请输入1-32位的字母、数字和下划线'))
        return
      }
      if (data.value.trim().length < 1 || data.value.trim().length > 512) {
        callback(new Error(note + '.value 请输入1-512位的字符'))
        return
      }
    }
  }else{
    let a = true
    Object.keys(faceDataInfo).forEach((item) => {
      if (item === 'faceData') {
        for (let i = 0; i < faceDataInfo[item].length; i++) {
          let note = 'faceData[' + i + ']'
          if (faceDataInfo[item][i].key.trim() === '' || faceDataInfo[item][i].key === null) {
            ElMessage.error('请完成表单信息！请输入' + item + '[' + i + '].key')
            a = false
          }
          if (faceDataInfo[item][i].value.trim() === '' || faceDataInfo[item][i].value.trim() === null) {
            ElMessage.error('请完成表单信息！请输入' + item + '[' + i + '].value')
            a = false
          }
        }
      } else if (faceDataInfo[item] === '' || faceDataInfo[item] === null) {
        ElMessage.error('请完成表单信息！请输入' + item)
        a = false
      }
    })
    return a
  }
}


const ruleFormRef = ref()
const rules = reactive<FormRules<typeof faceDataInfo>>({
  namespace: [
    {required: true, message: '请输入命名空间', trigger: 'blur'},
    {min: 1, max: 12, message: '长度在 1到 12 个字符', trigger: 'blur'},
    {pattern: regs.name, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  collectionName: [
    {required: true, message: '请输入集合名称', trigger: 'blur'},
    {min: 1, max: 24, message: '长度在 1到 24 个字符', trigger: 'blur'},
    {pattern: regs.name, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  faceData: [
    {required: true, message: '请输入样本属性字段', trigger: 'blur'},
    {validator: verify}
  ],
  sampleId: [
    {required: true, message: '请输入样本ID', trigger: 'blur'},
    {min: 1, max: 32, message: '长度在 1到 32 个字符', trigger: 'blur'},
    {pattern: regs.id, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  imageBase64: [
    {required: true, message: '请输入图片', trigger: 'blur'}
  ],
  faceScoreThreshold: [],
  maxConfidenceThresholdWithOtherSample: [],
  minConfidenceThresholdWithThisSample: []
})

</script>
<template>
  <el-button type="primary" :icon="Back" @click="router.back()">返回</el-button>
  <el-form :model="faceDataInfo" label-width="auto" :rules="rules" ref="ruleFormRef" style="max-width: 100%">
    <el-form-item label="namespace（命名空间）：" prop="namespace">
      <el-input v-model="faceDataInfo.namespace"/>
    </el-form-item>
    <el-form-item label="collectionName（集合名称）：" prop="collectionName">
      <el-input v-model="faceDataInfo.collectionName"/>
    </el-form-item>
    <el-form-item label="sampleId（样本Id,创建样本时的ID）：" prop="sampleId">
      <el-input v-model="faceDataInfo.sampleId"/>
    </el-form-item>
    <el-form-item label="faceData（样本人脸数据字段）：" prop="faceData">
      <div v-for="(item,index) in faceDataInfo.faceData" :key="index" class="flex gap-4 mb-4">
        KEY:&nbsp;<el-input v-model="item.key" placeholder="请输入字段名称" style="width: 200px"/>&nbsp;

        VALUE:&nbsp;<el-input v-model="item.value" placeholder="请输入字段值" style="width: 200px"/>&nbsp;
      </div>
      &nbsp;
      <div>
        <el-button type="primary" @click="addColumn">添加</el-button>
        <el-button type="primary" @click="deleteColumn">删除</el-button>
      </div>
    </el-form-item>
    <span>人脸质量分数阈值(推荐值 0 ):&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <el-slider v-model="faceDataInfo.faceScoreThreshold" show-input/>
    <br>
    <span>人脸相似度的最小阈值(推荐值0):</span>
    <el-slider v-model="faceDataInfo.minConfidenceThresholdWithThisSample" show-input/>
    <br>
    <span>人脸相似度的最大阈值(推荐值0):</span>
    <el-slider v-model="faceDataInfo.maxConfidenceThresholdWithOtherSample" show-input/>
    <br>
    <span>人脸数据图片：</span>
    <el-upload
        class="avatar-uploader"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
    >
      <img v-if="faceDataInfo.imageBase64" :src="faceDataInfo.imageBase64" class="avatar" width="100"/>
      <el-icon v-else class="avatar-uploader-icon">
        <Plus/>
      </el-icon>
    </el-upload>

    <br>
    <el-button type="primary" @click="addFaceData" style="width: 50%;font-size: 20px;margin-left: 25%">
      创建
    </el-button>
  </el-form>

</template>

<style scoped>
.el-slider {
  max-width: 600px;
  display: flex;
  align-items: center;
}

span {
  float: left;
  margin-right: 20px;
}


.avatar-uploader {
  width: 100px;
  height: 100px;
  display: block;

  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #949494;
  width: 100px;
  height: 100px;
  text-align: center;
}


</style>